{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 官方文档地址：\n",
    "https://www.tornadoweb.org/en/stable/httpclient.html#http-client-interfaces"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 同步调用\n",
    "\n",
    "from tornado import httpclient\n",
    "\n",
    "http_client = httpclient.HTTPClient()\n",
    "try:\n",
    "    response = http_client.fetch(\"http://www.tornadoweb.org/en/stable/\")\n",
    "    print(response.body.decode(\"utf-8\"))\n",
    "except httpclient.HTTPError as e:\n",
    "    print(\"Error: \" + str(e))\n",
    "except Exception as e:\n",
    "    print(\"Error: \" + str(e))\n",
    "http_client.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 异步事件循环调用\n",
    "\n",
    "from tornado import httpclient\n",
    "import tornado\n",
    "\n",
    "\n",
    "async def func():\n",
    "    http_client = httpclient.AsyncHTTPClient()\n",
    "    try:\n",
    "        response = await http_client.fetch(\"http://www.tornadoweb.org/en/stable/\")\n",
    "    except Exception as e:\n",
    "        print(\"Error: %s\" % e)\n",
    "\n",
    "    else:\n",
    "        print(response.body.decode(\"utf-8\"))\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    ## tornado 全局唯一的事件循环对象\n",
    "    io_loop = tornado.ioloop.IOLoop.current()\n",
    "    ## run_sync 方法可以在运行完某个协程之后停止事件循环\n",
    "    # io_loop.run_sync(func)\n",
    "\n",
    "    ## asyncio 方法执行\n",
    "    import asyncio\n",
    "\n",
    "    ## run_forever()\n",
    "    # asyncio.ensure_future(func())\n",
    "    # asyncio.get_event_loop().run_forever()\n",
    "\n",
    "    ## run_until_complete()\n",
    "    asyncio.get_event_loop().run_until_complete(func())\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
